<template>
  <div>
    <div class="pageTitleWhole">
      <a-breadcrumb>
        <a-breadcrumb-item>
          <router-link to="/landCenter/tractorManagement">牵引车管理</router-link>
        </a-breadcrumb-item>
        <a-breadcrumb-item>添加车辆</a-breadcrumb-item>
      </a-breadcrumb>
    </div>
    <div style="margin: 24px;">
      <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-card>
          <div class="card-title">
            选择类型
            <a-radio-group
              name="isSelfOperation"
              v-model="form.isSelfOperation"
              @change="() => {this.custIdList = []; this.form.custId=''}"
              style="marginLeft: 30px;"
            >
              <a-radio :value="1">自营车辆</a-radio>
              <a-radio :value="0">外派车辆</a-radio>
            </a-radio-group>
          </div>
        </a-card>
        <a-card>
          <div class="card-title hasContent">车辆档案</div>
          <a-row>
            <a-col :span="12">
              <a-form-model-item prop="typeId" label="车辆类型">
                <a-select v-model="form.typeId">
                  <a-select-option value>请选择</a-select-option>
                  <a-select-option v-for="c in typeList" :key="c.dictionaryId">{{c.name}}</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item prop="kerbMass" label="整备质量(kg)">
                <a-input-number v-model="form.kerbMass" :min="0" :max="999999" style="width: 100%" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item prop="truckNumber" label="车牌号">
                <a-input v-model="form.truckNumber" :max-length="7" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item prop="emissionStandard" label="车辆排放标准">
                <a-select v-model="form.emissionStandard">
                  <a-select-option value>请选择</a-select-option>
                  <a-select-option key="国三">国三</a-select-option>
                  <a-select-option key="国四">国四</a-select-option>
                  <a-select-option key="国五">国五</a-select-option>
                  <a-select-option key="国六">国六</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item prop="brandId" label="品牌型号">
                <a-select show-search v-model="form.brandId">
                  <a-select-option value>请选择</a-select-option>
                  <a-select-option v-for="c in brandList" :key="c.dictionaryId">{{c.name}}</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="12" style="height: 64px;">
              <a-form-model-item label="油耗系数(L/km)" prop="oilConsumption">
                <a-row :gutter="[10]">
                  <a-col :span="12">
                    <a-input-group compact>
                      <a-input value="双重" disabled style="width: 55px;" />
                      <a-input-number
                        v-model="form.doubleOilConsumption"
                        :min="0"
                        :precision="2"
                        @blur="validateOilConsumptionResult"
                        style="width: 110px"
                      />
                    </a-input-group>
                  </a-col>

                  <a-col :span="12">
                    <a-input-group compact>
                      <a-input value="单重" disabled style="width: 55px" />
                      <a-input-number
                        v-model="form.singleOilConsumption"
                        :min="0"
                        :precision="2"
                        @blur="validateOilConsumptionResult"
                        style="width: 110px"
                      />
                    </a-input-group>
                  </a-col>
                </a-row>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="所属车队" prop="custId">
                <a-select
                  show-search
                  :show-arrow="false"
                  :filter-option="false"
                  :default-active-first-option="false"
                  :not-found-content="null"
                  v-model="form.custId"
                  @search="handleNameChange"
                  @select="emptyChange"
                >
                  <a-select-option value>请选择</a-select-option>
                  <a-select-option v-for="d in custIdList" :key="d.id">{{ d.name }}</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="12" style="height: 64px;">
              <a-form-model-item label="油耗系数(L/km)" prop="emptyOilConsumption">
                <a-input-group compact>
                  <a-input value="空车" disabled style="width: 55px" />
                  <a-input-number
                    v-model="form.emptyOilConsumption"
                    :min="0"
                    :precision="2"
                    style="width: 110px"
                  />
                </a-input-group>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item prop="nuclearLoadMass" label="核定载质量(kg)">
                <a-input-number
                  v-model="form.nuclearLoadMass"
                  :min="0"
                  :max="999999"
                  style="width: 100%"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="12" v-if="form.isSelfOperation === 1">
              <a-form-model-item prop="maintenanceTime" label="下次保养时间">
                <a-date-picker
                  v-model="form.maintenanceTime"
                  @change="onChangeMaintenanceTime"
                  style="width: 100%"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item prop="totalMass" label="总质量(kg)">
                <a-input-number
                  v-model="form.totalMass"
                  :min="0"
                  :max="999999"
                  style="width: 100%"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="12" v-if="form.isSelfOperation === 1">
              <a-form-model-item prop="reviewTime" label="下次年审时间">
                <a-date-picker
                  v-model="form.reviewTime"
                  @change="onChangeReviewTime"
                  style="width: 100%"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="12" v-if="form.isSelfOperation === 1">
              <a-form-model-item prop="imei" label="设备IMEI">
                <a-input v-model="form.imei" :max-length="20"></a-input>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-card>

        <a-card>
          <div class="card-title hasContent">车辆行驶证</div>
          <a-row>
            <a-col :span="12">
              <a-form-model-item prop="vin" label="车辆识别代号">
                <a-input v-model="form.vin" :max-length="20" />
              </a-form-model-item>
              <a-form-model-item prop="drivingPermitExpireTime" label="行驶证到期日期">
                <a-date-picker
                  v-model="form.drivingPermitExpireTime"
                  @change="onChangeDrivingPermitExpireTime"
                  style="width: 100%"
                />
              </a-form-model-item>
              <a-form-model-item prop="engineNumber" label="发动机号码">
                <a-input v-model="form.engineNumber" :max-length="10" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item prop="drivingPermitPics1" style="float: left;">
                <upload-identity-card
                  identityCardField="drivingPermitPics1"
                  identityCardText="上传行驶证"
                  @success="fileSuccess"
                  style="margin:4px 20px 0 0;"
                />
              </a-form-model-item>
              <a-form-model-item prop="drivingPermitPics2" style="float: left;">
                <upload-identity-card
                  identityCardField="drivingPermitPics2"
                  identityCardText="上传行驶证"
                  @success="fileSuccess"
                  style="margin:4px 20px 0 0;"
                />
              </a-form-model-item>
              <div class="drivePngts">上传png，jpg等格式，大小不超过2M</div>
            </a-col>
          </a-row>
        </a-card>

        <a-card>
          <div class="card-title hasContent">道路运输经营许可证</div>
          <a-row>
            <a-col :span="12">
              <a-form-model-item prop="operationCertificate" label="道路运营证字号">
                <a-input v-model="form.operationCertificate" :max-length="20" />
              </a-form-model-item>
              <a-form-model-item prop="operationCertificateBeginTime" label="道路运营证有效期">
                <a-range-picker @change="onChangeOperationCertificate" style="width: 100%">
                  <a-icon slot="suffixIcon" type="calendar" />
                </a-range-picker>
              </a-form-model-item>
              <a-form-model-item prop="operationCertificateReviewTime" label="证件年审日期">
                <a-date-picker
                  @change="onChangeOperationCertificateReviewTime"
                  style="width: 100%"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item prop="operationCertificatePics1" style="float: left;">
                <upload-identity-card
                  identityCardField="operationCertificatePics1"
                  identityCardText="上传营运证"
                  @success="fileSuccess"
                  style="margin:4px 20px 0 0;"
                />
              </a-form-model-item>
              <a-form-model-item prop="operationCertificatePics2" style="float: left;">
                <upload-identity-card
                  identityCardField="operationCertificatePics2"
                  identityCardText="上传营运证"
                  @success="fileSuccess"
                  style="margin:4px 20px 0 0;"
                />
              </a-form-model-item>
              <div class="drivePngts">上传png，jpg等格式，大小不超过2M</div>
            </a-col>
          </a-row>
        </a-card>
      </a-form-model>
    </div>
    <div class="creat_button">
      <a-button
        type="primary"
        @click="save"
        :saveLoading="saveLoading"
        style="margin-left: 20px; margin-top:12px; float: right"
      >提交</a-button>
      <a-button @click="cancelCreate" style="float: right; margin-top:12px;">取消</a-button>
    </div>
  </div>
</template>

<script>
import debounce from 'lodash/debounce'
import { queryCustNameList } from '@/api'
import UploadIdentityCard from '@/components/UploadIdentityCard'
import { queryDataDictionaryDown, addTruckInfo } from '@/api/landCenter'
const fomrMessage = `必填项不能为空`
// TRUCK_TYPE:车辆类型 TRUCK_BRAND:车辆品牌型号
const TRUCK_TYPE = 'TRUCK_TYPE'
const TRUCK_BRAND = 'TRUCK_BRAND'

export default {
  data () {
    this.handleNameChange = debounce(this.handleNameChange, 800)
    return {
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      custIdList: [], // 车队
      typeList: [], // 车辆类型
      brandList: [], // 品牌型号
      form: {
        tractorOrTrailer: 1,
        isSelfOperation: 1,
        custId: '', // 客户（车队）id
        typeId: '', // Integer车辆类型id
        truckNumber: '', // 车牌号
        brandId: '', // 品牌id
        nuclearLoadMass: '', // 核定载质量
        totalMass: '', // 总质量
        kerbMass: '', // 整备质量
        emissionStandard: '', // 车辆排放标准（创建车辆必传，挂车不用传）
        singleOilConsumption: '', // Short单重油耗（创建车辆必传，挂车不用传）
        doubleOilConsumption: '', // Long双重油耗（创建车辆必传，挂车不用传）
        emptyOilConsumption: '', // 1.1.5
        // inspectionTime: null, // 下次年检日期
        maintenanceTime: null, // 下次保养日期
        reviewTime: null, // 下次年审日期
        vin: '', // 车辆识别号
        drivingPermitExpireTime: null, // 行驶证到期日期
        engineNumber: '', // 发动机号码
        drivingPermitPics: '', // 行驶证图
        operationCertificate: '', // 车辆营运证号码
        operationCertificateBeginTime: null, // 车辆营运证生效日期
        operationCertificateEndTime: null, // 车辆营运证到期日期
        operationCertificateReviewTime: null, // 营运证年审日期
        operationCertificatePics: '', // 营运证图片
        imei: '',
        // not in form
        drivingPermitPics1: '',
        drivingPermitPics2: '',
        operationCertificatePics1: '',
        operationCertificatePics2: ''
      },
      rules: {
        typeId: [{ required: true, message: fomrMessage, trigger: ['blur', 'change'] }],
        kerbMass: [{ required: true, message: fomrMessage, trigger: 'blur' }],
        truckNumber: [{ required: true, message: fomrMessage, trigger: 'blur' }],
        emissionStandard: [{ required: true, message: fomrMessage, trigger: 'blur' }],
        brandId: [{ required: true, message: fomrMessage, trigger: ['blur', 'change'] }],
        oilConsumption: [{ required: true, validator: this.validateOilConsumption }],
        emptyOilConsumption: [{ required: true, validator: this.validateOilConsumption2 }],
        custId: [{ required: true, message: fomrMessage, trigger: ['blur', 'change'] }],
        nuclearLoadMass: [{ required: true, message: fomrMessage, trigger: 'blur' }],
        maintenanceTime: [{ required: true, message: fomrMessage, trigger: ['blur', 'change'] }],
        totalMass: [{ required: true, message: fomrMessage, trigger: 'blur' }],
        reviewTime: [{ required: true, message: fomrMessage, trigger: ['blur', 'change'] }],
        vin: [{ required: true, message: fomrMessage, trigger: 'blur' }, { message: '只能输入字母和数字', pattern: /^[a-zA-Z0-9]+$/, trigger: 'blur' }],
        engineNumber: [{ required: true, message: fomrMessage, trigger: 'blur' }, { message: '只能输入字母和数字', pattern: /^[a-zA-Z0-9]+$/, trigger: 'blur' }],
        operationCertificate: [{ required: true, message: fomrMessage, trigger: 'blur' }, { message: '只能输入字母和数字', pattern: /^[a-zA-Z0-9]+$/, trigger: 'blur' }],
        drivingPermitExpireTime: [{ required: true, message: fomrMessage, trigger: ['blur', 'change'] }],
        drivingPermitPics1: [{ required: true, message: fomrMessage, trigger: 'blur' }],
        drivingPermitPics2: [{ required: true, message: fomrMessage, trigger: 'blur' }],
        operationCertificateReviewTime: [{ required: true, message: fomrMessage, trigger: ['blur', 'change'] }],
        operationCertificatePics1: [{ required: true, message: fomrMessage, trigger: 'blur' }],
        operationCertificatePics2: [{ required: true, message: fomrMessage, trigger: 'blur' }],
        imei: [{ required: true, message: fomrMessage, trigger: 'blur' }]
      },
      saveLoading: false
    }
  },
  components: {
    [UploadIdentityCard.name]: UploadIdentityCard
  },
  created () {
    this.initListData()
  },
  methods: {
    handleNameChange (nameLike = '') { // 车队
      queryCustNameList({
        nameLike,
        belongCompany: 'JIA_TE',
        custTypeLike: this.form.isSelfOperation === 1 ? 'SELF_TEAM' : (this.form.isSelfOperation === 0 ? 'EXPATRIATE_TEAM' : 'TEAM'),
        status: 1
      }).then(rsp => {
        this.custIdList = rsp.data
      })
    },
    emptyChange (e) {
      this.handleNameChange()
    },
    initListData () {
      queryDataDictionaryDown({ type: TRUCK_TYPE }).then(rsp => {
        this.typeList = rsp.data
      })

      queryDataDictionaryDown({ type: TRUCK_BRAND }).then(rsp => {
        this.brandList = rsp.data
      })
    },
    validateOilConsumption (rule, value, callback) {
      if (!this.form.doubleOilConsumption || !this.form.singleOilConsumption) {
        callback(new Error(fomrMessage))
      } else {
        callback()
      }
    },
    validateOilConsumption2 (rule, value, callback) {
      if (!this.form.emptyOilConsumption) {
        callback(new Error(fomrMessage))
      } else {
        callback()
      }
    },
    validateOilConsumptionResult () {
      this.$refs['ruleForm'].validateField('oilConsumption')
    },
    onChangeOperationCertificateReviewTime (date, dateStr) {
      this.form.operationCertificateReviewTime = dateStr
    },
    onChangeOperationCertificate (date, dateStr) {
      this.form.operationCertificateBeginTime = dateStr[0]
      this.form.operationCertificateEndTime = dateStr[1]
    },
    onChangeInspectionTime (date, dateStr) {

    },
    onChangeMaintenanceTime (date, dateStr) {

    },
    onChangeReviewTime (date, dateStr) {

    },
    onChangeDrivingPermitExpireTime (date, dateStr) {

    },
    fileSuccess (key, url) {
      if (key === 'drivingPermitPics1') {
        this.form.drivingPermitPics1 = url
      } else if (key === 'drivingPermitPics2') {
        this.form.drivingPermitPics2 = url
      } else if (key === 'operationCertificatePics1') {
        this.form.operationCertificatePics1 = url
      } else if (key === 'operationCertificatePics2') {
        this.form.operationCertificatePics2 = url
      }
    },
    cancelCreate () {
      let _t = this
      this.$confirm({
        title: '还有未保存的信息，退出后编辑的数据将消失，确定退出？',
        onOk () {
          _t.$router.push({ name: 'landCenter/tractorManagement' })
        }
      })
    },
    save () {
      this.saveLoading = true
      this.$refs['ruleForm'].validate(valid => {
        if (valid) {
          // 图片地址
          this.form.drivingPermitPics = this.form.drivingPermitPics1 + ',' + this.form.drivingPermitPics2
          this.form.operationCertificatePics = this.form.operationCertificatePics1 + ',' + this.form.operationCertificatePics2

          addTruckInfo(this.form).then(rsp => {
            this.$message.success('提交成功！')
            this.saveLoading = false
            this.$router.push({ name: 'landCenter/tractorManagement' })
          }).catch(rs => { this.saveLoading = false })
        }
      })
    }
  },
  mounted () {
    this.handleNameChange()
  }
}
</script>

<style lang="less" scoped>
.ant-card {
  margin-bottom: 24px;
  border: none;
  .card-title {
    position: relative;
    padding-left: 16px;
    font-size: 18px;
    line-height: 1;
    color: #000;
    &:before {
      content: '';
      width: 5px;
      height: 18px;
      background: #1890ff;
      border-radius: 4px;
      position: absolute;
      left: 0;
      top: -1px;
    }
  }
  .hasContent {
    margin-bottom: 20px;
  }
}
.drivePngts {
  position: absolute;
  bottom: -15px;
  color: rgba(0, 0, 0, 0.45);
}
.ant-col-12 {
  padding-right: 50px;
}
</style>
